<!--/**
* @author xuyh0817
* @email xuyh0817@foxmail.com
* @date 2022-02-16 15:58
* @version 2.0.0
* @doc todo
* @website todo
* @remark  如果要分发源码，需在本文件顶部保留此文件头信息！！
*/
-->
<template>
  <div v-if="hasInput" class="x-slider-container">
    <div class="x-slider-item">
      <a-slider
        :value="currentValue"
        v-bind="attrs"
        :marks="marks"
        :range="false"
        @change="changeHandler"
      />
    </div>

    <div class="x-slider-input">
      <a-input-number
        style="width: 70px!important;"
        :value="currentValue"
        v-bind="inputNumberAttrs"
        @change="changeHandler"
      />
    </div>
  </div>

  <a-slider
    v-else
    :value="currentValue"
    v-bind="attrs"
    :marks="marks"
    :range="false"
    @change="changeHandler"
  />
</template>

<script>
import {COMPONENT_TYPE, CUSTOM_EVENT_TYPE} from '../../constants'
import ComponentMixin from '../../XRenderMixins/XRenderComponentMixin'

export default {
  name: COMPONENT_TYPE.SLIDER,
  mixins: [ComponentMixin],
  props: {
    value: {
      type: [Number]
    }
  },
  computed: {
    currentValue: {
      get() {
        const {value} = this
        return value ? (typeof (value) === 'number' ? value : 0) : 0
      }
    },
    marks: {
      get() {
        const {attrs, formItem, isDebug} = this
        const {marks} = attrs
        if (typeof (marks) !== 'string' && typeof (marks) !== 'object') {
          isDebug ? console.warn(`${formItem.prop} marks类型错误,非String或Object`) : ''
          return {}
        }
        if (typeof (marks) === 'object') {
          return marks
        }
        return (new Function('return ' + marks))()
      }
    },
    hasInput: {
      get() {
        const {attrs} = this
        const {hasInput} = attrs
        return !!hasInput && typeof (hasInput) === 'boolean' ? hasInput : false
      }
    },
    inputNumberAttrs: {
      get() {
        const {attrs} = this
        const {max, min, step} = attrs
        return {
          max,
          min,
          step
        }
      }
    }
  },
  methods: {
    changeHandler(value) {
      const {formItem, attrs} = this
      this.$emit(CUSTOM_EVENT_TYPE.CHANGE, {
        type: COMPONENT_TYPE.SLIDER,
        prop: formItem ? formItem.prop : '',
        value,
        attrs,
        formItem
      })
    }
  }
}
</script>

<style scoped lang="css">
.x-slider-container {
  width: 100%;
  display: flex;
  flex-flow: row nowrap;
  justify-content: flex-start;
  align-items: center;
  align-content: center;
}

.x-slider-item {
  width: calc(100% - 70px);
}

.x-slider-input {
  width: 70px;
}
</style>
